package com.asset.dispoal.file.replyDetail.domain.service.excelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.asset.dispoal.file.replyDetail.domain.dto.ReplyDetailExportTemplate;
import com.asset.dispoal.file.replyDetail.domain.service.command.FileReplyDetailExcelDataSaveCommand;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import tech.mhuang.pacebox.core.timer.SystemClock;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qr
 * @date 2021/11/24$
 */
@Data
@Slf4j
public class ReplyDetailExcelListener extends AnalysisEventListener<ReplyDetailExportTemplate> {


    private FileReplyDetailExcelDataSaveCommand fileExcelDataSaveCommand;

    private static Map<String, Object> map = new HashMap<>(2);

    public ReplyDetailExcelListener(FileReplyDetailExcelDataSaveCommand fileExcelDataSaveCommand) {
        this.fileExcelDataSaveCommand = fileExcelDataSaveCommand;
        map.put("dataList", list);
    }

    /**
     * 批处理阈值
     */
    private static final int BATCH_COUNT = 2000;
    List<ReplyDetailExportTemplate> list = new ArrayList<>(BATCH_COUNT);

    @Override
    public void invoke(ReplyDetailExportTemplate bsDataDetailExportTemplate, AnalysisContext analysisContext) {
        list.add(bsDataDetailExportTemplate);
        if (list.size() >= BATCH_COUNT) {
            long startTime = SystemClock.now();
            this.fileExcelDataSaveCommand.execute(map);
            log.info("存储数据成功！用时{}ms", SystemClock.now() - startTime);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        this.fileExcelDataSaveCommand.execute(map);
        list.clear();
    }
}
